<template>
  <!-- 放款记录 -->
  <div class="ContactPerson" >
    <div class="searchNav">
      <!-- <h2>联系人</h2> -->
      <!--  <el-button class="button" icon="el-icon-plus" type="primary" style="margin-left: 0"
        @click="handleAdd">新增</el-button> -->
      <div class="block">
        <el-date-picker
          v-model="range"
          type="daterange"
          style="width: 250px; margin-left: 10px"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="changeTime"
        >
        </el-date-picker>
      </div>
      <div class="searchParams">
        <el-input
          class="input"
          v-model="searchKeyword.Keyword"
          placeholder="请输入赊货方/销售方"
          clearable
          @keydown.enter.native="getDataList"
        ></el-input>
        <el-button type="primary" class="button" @click="search"
          >查询</el-button
        >
        <el-button class="button" @click="reset('reset')">重置</el-button>
      </div>
      <el-tag
        type="success"
        size="medium"
        effect="plain"
        style="font-size: 17px; font-weight: bold"
        >赊货总计<span
          style="margin-right: 5px; font-size: 17px; font-weight: bold"
          >:{{ toThousands(summaryTotalData[0].sheHuoTotalMoney) }}</span
        ></el-tag
      >
    </div>
    <div>
      <el-table
        :data="tableData"
        style="width: 100%"
        :max-height="height"
        show-summary
        :summary-method="getSummaries"
      >
        <!-- <el-table-column prop="SupplieName" label="银行名称">
          <template slot-scope="scope">
            <span>{{ scope.row.CreateTime.substring(0, 10) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="BuyerName" label="赊货方">
          <template slot-scope="scope">
            <el-link @click="handlelDetail(scope.row)">{{
              scope.row.BuyerName
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="CompanyName" label="销售方"> </el-table-column>
        <el-table-column prop="CreateTime" label="赊货日期">
          <template slot-scope="scope">
            <span>{{
              scope.row.CreateTime ? scope.row.CreateTime.substring(0, 10) : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="LoanTime" label="放款日期">
          <template slot-scope="scope">
            <span>{{
              scope.row.LoanTime ? scope.row.LoanTime.substring(0, 10) : ""
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="LoanAmount" label="放款金额">
          <template slot-scope="scope">
            <span>{{ toThousands(scope.row.LoanAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ReceiveSum" label="赊货金额">
          <template slot-scope="scope">
            <span>{{ toThousands(scope.row.TotalSum) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="IsLoan" label="是否放款">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsLoan==true" >已放款</el-tag>
            <el-tag v-else type="danger">待放款</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="LoanRemarks" label="放款备注"> </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="!scope.row.IsLoan"
              @click="handleDelete(scope.row)"
              style="color: #409eff"
              >放款</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部统计 -->
      <!-- <summaryTableTotalVue :summary-total-data="summaryTotalData" :table-column-data="tableColumnData"
        ref="summaryTableTotalVue" :parentObj="{ ...this }"></summaryTableTotalVue> -->
      <!-- 分页 -->
      <div style="display: flex; justify-content: flex-end; margin-top: 8px">
        <pagination
          :total="pagination.total"
          :page.sync="pagination.PageIndex"
          :limit.sync="pagination.PageRows"
          @pagination="handlePageChange"
        />
      </div>
    </div>
    <EditForm ref="editForm" :parentObj="{ ...this }" />

    <el-dialog title="放款" :visible.sync="Loan.dialogLoan" width="30%">
      <el-input v-model="Loan.LoanValue" placeholder="请输入备注"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="loanRemarkCancel">取 消</el-button>
        <el-button type="primary" @click="loanRemarkConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 资质详情 -->
    <MyMerchantDetail ref="MyMerchantDetail" :parentObj="{ ...this }" />
  </div>
</template>

<script>
import radioGroup from "@/components/CompanyRadioGroup.vue";
import { toThousands } from "@/utils/Tools";
import EditForm from "./LoanRecordsForm.vue";
// 引入表格统计组件
import summaryTableTotalVue from "../../components/summaryTableTotal.vue";
// 引入资质详情组件 统一用的是我的商户页面里的资质详情
import MyMerchantDetail from "../MyMerchant/MyMerchantDetail.vue";
export default {
  name: "LoanRecords",
  props: {},
  components: {
    EditForm,
    radioGroup,
    summaryTableTotalVue,
    MyMerchantDetail,
  },
  computed: {
    height() {
      let height = document.documentElement.clientHeight * 0.75;
      return height;
    },
  },
  data() {
    return {
       // 整体页面加载
       fullscreenLoading:false,
      // 时间范围
      range: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        pageSizeOptions: [10, 50, 100],
      },
      sorter: {
        field: "CreateTime",
        order: "desc",
      },
      // 表格底部统计列表列数
      tableColumnData: [
        {
          prop: "summaryTotalText",
          label: "总计",
        },
        {
          prop: "",
          label: "",
        },
        {
          prop: "",
          label: "",
        },
        {
          prop: "",
          label: "",
        },
        {
          prop: "fangkuanMoney",
          label: "",
        },
        {
          prop: "shehuoMoney",
          label: "",
        },
        {
          prop: "",
          label: "",
        },
        {
          prop: "",
          label: "",
        },
      ],
      summaryTotalData: [
        {
          summaryTotalText: "总计",
          // 赊货总计
          sheHuoTotalMoney: 0,
          fangkuanMoney: 0,
          shehuoMoney: 0,
        },
      ],
      tableData: [],
      queryParam: {
        CompanyId:
          "1620979870186082305,1630102749423079424,1630778196955762689,1630800038118559744,1631186997005520896,1632933237242204161,1634096431549648896,1643873497987944448,1646713156308832256",
      },
      loading: false,
      toThousands,
      // 用户字段
      userIdList: [],
      // 放款
      Loan: {
        // 是否放款
        Lending: false,
        // 放款备注
        dialogLoan: false,
        LoanValue: "",
        userId: "",
      },
      // 搜索关键字
      searchKeyword: {
        Keyword: "",
        LoanTime: "",
        StartDate: "",
        EndDate: "",
      },
      fangkuanList: [],
      shehuoList: [],
    };
  },
  mounted() {
    // 获取放款管理列表数据
    this.getDataList();
  },
  created() {},
  methods: {
    //自定义方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = {};
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 4) {
          sums[index] = this.toThousands(
            this.summaryTotalData[0].fangkuanMoney
          );
          return;
        }
        if (index === 5) {
          sums[index] = this.toThousands(this.summaryTotalData[0].shehuoMoney);
          return;
        }
        // const values = data.map(item => Number(item[column.property]));
        // if (column.label == "水份含量(%)" || column.label == "原料重量(kg)") {
        //   if (!values.every(value => isNaN(value))) {
        //       sums[index] = values.reduce((prev, curr) => {
        //           const value = Number(curr);
        //           if (!isNaN(value)) {
        //               return prev + curr;
        //           } else {
        //               return prev;
        //           }
        //       }, 0);
        //       // sums[index] += ' kg';
        //   } else {
        //       // sums[index] = 'N/A';
        //   }
        // }
      });
      return sums;
    },
    // 获取顶部统计金额数据
    GetTotalCredit(data) {
      this.$http
        .post("/Base/Bank_Info/GetTotalCredit", {
          Search: {
            userids: data,
            Keyword: this.searchKeyword.Keyword,
            StartDate: this.searchKeyword.StartDate,
            EndDate: this.searchKeyword.EndDate,
          },
        })
        .then((resJson) => {
          if (resJson.Success) {
            console.log("获取顶部统计金额", resJson.Data.CreditAmount);
            this.summaryTotalData[0].sheHuoTotalMoney =
              resJson.Data.CreditAmount;
          }
        });
    },
    // 获取底部统计金额数据 分页
    GetTotalBtmCredit(data) {
      this.$http
        .post("/Base/Bank_Info/GetTotalBtmCredit", {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: "CreateTime",
          SortType: "desc",
          Search: {
            userids: data,
            Keyword: this.searchKeyword.Keyword,
            StartDate: this.searchKeyword.StartDate,
            EndDate: this.searchKeyword.EndDate,
          },
        })
        .then((resJson) => {
          if (resJson.Success) {
            console.log("获取底部统计金额===", resJson.Data);
            this.summaryTotalData[0].fangkuanMoney = resJson.Data.Amounttwo;
            this.summaryTotalData[0].shehuoMoney = resJson.Data.CreditAmount;
          }
        });
    },
    // 商铺资质详情跳转
    handlelDetail(row) {
      console.log("资质详情", row);
      if (row.BuyerStoreId) {
        this.$refs.MyMerchantDetail.openForm(row.BuyerStoreId);
      } else {
        this.$message.error("没有店铺信息");
      }
    },
    // 开始结束时间选择
    changeTime(e) {
      this.range = e;
      console.log("开始时间", e, this.queryParam);
      this.searchKeyword.StartDate = this.range[0];
      this.searchKeyword.EndDate = this.range[1];
      // 刷新放款列表
      this.tableData = [];
      this.pagination.current = 1;
      this.getDataList();
    },
    // 参数重置
    reset(event) {
      if (event === "reset") {
        this.range = [];
        this.searchKeyword.StartDate = "";
        this.searchKeyword.EndDate = "";
      }
      this.pagination.current = 1;
      this.tableData = [];
      this.getDataList();
    },
    // 搜索
    search() {
      this.reset();
    },
    // 新增放款记录
    handleAdd() {
      this.$refs.editForm.openForm();
    },
    handleView(row) {
      this.$refs.editForm.openForm(row.Id);
    },
    // 放款动作
    handleDelete(row) {
      this.Loan.dialogLoan = true;
      this.Loan.userId = row.Id;
      // 每次打开弹窗清空输入框内容
      this.Loan.LoanValue = "";
    },
    // 备注确定
    loanRemarkConfirm() {
      var that = this;
      console.log(this.Loan.userId);
      this.$confirm("确定为该用户进行放款嘛?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((result) => {
          this.LoanRequestData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "放款已取消",
          });
          this.Loan.userId = "";
        });
    },
    //备注取消
    loanRemarkCancel() {
      this.Loan.dialogLoan = false;
      this.Loan.LoanValue = "";
    },

    // 分页函数
    handlePageChange(data) {
      this.pagination.current = data.pageIndex;
      this.pagination.pageSize = data.pageSize;
      this.getDataList(); //这是重新获取修改日志列表
    },
    //  获取放款管理列表数据
    getDataList() {
      let userId = JSON.parse(sessionStorage.getItem("userInfo"));
      this.$http
        .post(`/Base/Bank_Info/Getuserids?Id=${[userId.Id]}`)
        .then((res) => {
          this.userIdList = res.Data;
          if (res.Success) {
            this.loanlistData(res.Data);
            // 获取顶部统计金额数据  总数据
            this.GetTotalCredit(res.Data);
            // 获取底部统计金额数据   分页统计数据
            this.GetTotalBtmCredit(res.Data);
          }
        });
    },
    // 获取放款管理列表数据
    loanlistData(data) {
      var that = this
      //创建loading对象开始遮罩
      this.loading = true;
      this.$http
        .post("/Base/Bank_Info/GetBillingData", {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: "CreateTime",
          SortType: "desc",
          Search: {
            userids: data,
            Keyword: this.searchKeyword.Keyword,
            StartDate: this.searchKeyword.StartDate,
            EndDate: this.searchKeyword.EndDate,
          },
        })
        .then((resJson) => {
          if (resJson.Success) {
            //请求结束关闭loading
            setTimeout(function () {
            that.loading = false;
          }, 600);
            this.tableData = resJson.Data;
            if (this.tableData) {
              const pagination = { ...this.pagination };
              pagination.total = resJson.Total;
              this.pagination = pagination;
            }
          } else {
            //请求结束关闭loading
            setTimeout(function () {
              rLoading.close();
            }, 500);
          }
        });
    },
    // 放款功能函数
    LoanRequestData() {
      var that = this;
      //创建loading对象开始遮罩
      const rLoading = this.openLoading();
      // 后续这里尽量分出一个函数来单独调用。否则太乱。不容易读代码
      this.$http
        .post("/Base/Bank_Info/OrderDisbursement", {
          Id: this.Loan.userId,
          LoanRemarks: this.Loan.LoanValue,
        })
        .then((res) => {
          if (res.Success) {
            this.Loan.userId = "";
            //请求结束关闭loading
            setTimeout(function () {
              rLoading.close();
            }, 500);
            this.$message({
              type: "success",
              message: "放款成功!",
            });
            // 关闭弹窗
            that.Loan.dialogLoan = false;
            that.getDataList();
          } else {
            this.$message({
              type: "success",
              message: res.Msg,
            });
          }
        });
    },
  },
  watch: {},
};
</script>

<style lang="less" scoped>
.searchNav .searchParams {
  justify-content: left;
}
</style>
